## You need the following if this is ever being run as a script 
import os, sys  
  
sys.path.insert(0, "C:\Documents and Settings\wendy_admin\src\eclipse_workspace\djangodb\main")  
if not os.environ.has_key("DJANGO_SETTINGS_MODULE"):
    os.environ["DJANGO_SETTINGS_MODULE"]="formstates_wjContact.settings"
    




from django import newforms as forms

from formstates_wjContact.views.widgets import DeleteCheckbox, EnglishNamesMultiWidget
from formstates_wjContact.contacts.exceptions import MultiWidgetException

from formstates_wjContact.contacts.models import Contact, Recipient, Volunteer
from formstates_wjContact.contacts.models import GroupService, Group
from formstates_wjContact.contacts.models import Language, UserLanguage


from formstates_wjContact.contacts.models import Phone
import datetime




## Here we make classes to represent the various kinds of forms we are
## going to use.
PHONE_CHOICES = Phone.PHONE_CHOICES





class PhoneDeleteCheckbox(forms.widgets.CheckboxInput):
# Here is the render method for a plain Input type input, which is the 
# base-class for all inputs except radio and checkbox...
#	def render(self, name, value, attrs=None):
#        if value is None: value = ''
#        final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
#        if value != '': final_attrs['value'] = smart_unicode(value) # Only add the 'value' attribute if a value is non-empty.
#        return u'<input%s />' % flatatt(final_attrs)
#
# And here is the render method for a Checkboxinput
#    def render(self, name, value, attrs=None):
#        final_attrs = self.build_attrs(attrs, type='checkbox', name=name)
#        try:
#            result = self.check_test(value)
#        except: # Silently catch exceptions
#            result = False
#        if result:
#            final_attrs['checked'] = 'checked'
#        if value not in ('', True, False, None):
#            final_attrs['value'] = smart_unicode(value) # Only add the 'value' attribute if a value is non-empty.
#        return u'<input%s />' % flatatt(final_attrs)

    def render(self, name, value, attrs=None):
    	output=forms.widgets.CheckboxInput.render(self, name, value, attrs={'id':attrs['id']})
        if 'id' in attrs:
    	    id = attrs['id']
    	    label = "<label class=phone_delete_label for=%s> Delete this phone-entry? </label>" % attrs['id']
    	return label+output
 
    
class PhoneWidget(EnglishNamesMultiWidget):
    """ """
    phone_id_fieldname = '%s_phone_id'
    phone_number_fieldname = '%s_phone_number'
    phone_type_fieldname = '%s_phone_type'
    phone_delete_fieldname = '%s_phone_delete'

    widget_to_database = {
                       'phone_id': phone_id_fieldname,
                       'phone_number': phone_number_fieldname,
                       'phone_type': phone_type_fieldname,
                       }
    database_to_widget = {
                       'id': 'phone_id',
                       'phone_number': 'phone_number',
                       'phone_type': 'phone_type',
                       }


    def __init__(self, attrs=None):
        """
        Initialise this multiwidget by passing in the three widgets 
        required, then calling the __init__ method of the superclass.
        """
        widgets = (forms.HiddenInput(attrs={'widget_name': 'phone_id'}),
                   forms.TextInput(attrs={'widget_name': 'phone_number'}), 
                   forms.Select(attrs={'widget_name': 'phone_type'}, choices=(PHONE_CHOICES)),
                   DeleteCheckbox(
                       attrs={
                              'widget_name': 'phone_delete', 
                              'id_suffix': 'phone_delete_id'
                             } ,
                       ## We want the box unchecked when first rendered ;) 
                       check_test=False),
                   )
        super(PhoneWidget, self).__init__(widgets, attrs)
    
    def render(self, name, value, attrs=None):
        """
         name - fieldname - 'phone_1', 'phone_1', etc
         value - [phone_id, phone_number, phone_type, phone_delete]
          or "36#481-5672#landline-home#"
         
        """
      
        if not isinstance(value, list):
            value = self.decompress(value)
        ## If we are a new_entry, and there is a 'delete' check-box, get rid of
        ## it (new_entries should never be deleted as they are not yet in the 
        ## database anyway! Having this checkbox there will do nothing useful,
        ## possibly generate errors, and generally confuse the user...)
        if value[0] == 'new_entry' and len(self.widgets) == 4:
            del self.widgets[3]  
        return EnglishNamesMultiWidget.render(self, name, value, attrs)
 
    def decompress(self, value):
        """
        Returns a list of decompressed values for the given compressed value.
        The given value can be assumed to be valid, but not necessarily
        non-empty. 
        """
        if value:
            return value.split('#')
        raise Exception, "No value to decompress in PhoneWidget"
    
    def save_to_database(self, data, contact_id, name):
        ## Doing this here rather than on the Field object as here seems to be
        ## where we have the most knowledge of ie the constituent part names
        ## and so on.      
        current_values = self.value_from_datadict(data, name)
        
        phone_number = current_values[1]
        phone_type = current_values[2]
        phone_delete = current_values[3]
        

        if current_values[0] == 'new_entry':
            phone_id = None
        else: 
            phone_id = current_values[0]
           
        if phone_delete and phone_delete <> 'no-delete':
            ## try deleting - only possible of course if this entry already 
            ## exists!
            if phone_id:
                Phone.objects.get(pk=phone_id).delete()
                return
            raise KeyError, "No value for phone_id passed into save_to_database() method for a PhoneWidget"
        ## Or, if we are saving/creating.
        contact=Contact.objects.get(pk=contact_id)
        if phone_id:
            ## We have a  phone_id, so this must be an
            ## existing entry. Possibly though we have changed the 
            ## number or type of this phone. So wipe over previous values. 
            existing_phone = Phone.objects.get(pk=phone_id)
            existing_phone.phone_number = phone_number
            existing_phone.phone_type = phone_type
            existing_phone.save()            
        else: 
            new_phone = Phone(phone_number = phone_number, 
                phone_type = phone_type, contact=contact)
            new_phone.save()
                
    def value_from_datadict(self, data, name):
        
        phone_id = data.get(self.phone_id_fieldname % name)
        phone_number = data.get(self.phone_number_fieldname % name)
        phone_type = data.get(self.phone_type_fieldname % name)
        phone_delete = data.get(self.phone_delete_fieldname % name) 
        ## If there was anything present at all under 'phone_delete'
        if phone_delete:          
            phone_delete = 'delete'
        if not phone_delete:
            phone_delete = 'no-delete'         
        
        x= [phone_id, phone_number, phone_type, phone_delete]
        if (not x[0]):
            raise MultiWidgetException, "Problem getting PhoneWidget value out of data dictionary ..."  
        return  x   				

class LanguageFieldsWidget(forms.MultiWidget):
    """
    A Widget that splits language input into three seperate html widgets:
    
    -  <input type="text">  for the actual language-name.
    -  <input type="select">  for the usage-type (spoken, written, etc).
    -  <input type="select">  for the user's preference for this language
        (prmary or secondary).
      
    Designed to be used with the LanguageFields() class.
       
    """
    language_name_field = '%s_language_name'
    language_usage_field = '%s_language_usage'
    language_preferred_field = '%s_language_preferred'

    def __init__(self, attrs=None):
        """
        Initialise this multiwidget by passing in the three widgets 
        required, then calling the __init__ method of the superclass.
        The last two widgets are select-boxes so they need to have the correct 
        choices-list passed in as well.
        """
#        if attrs:
#            if 'choices' in attrs:
#                lang_choices=choices
#        else:
#            lang_choices = ["Gherkin", "Tomato" ] 
        print "in  LanguageFieldsWidget.__init__()..."
        lang_choices = (
                            
        ('eggs', 'Eggs'),
        ('tomato', 'Tomato'),
        ('gherkin', 'Gherkin'),
        
                       ) 
                    
        widgets = (
                   forms.Select(attrs={'widget_name': 'language_name'}, choices=(lang_choices)), 
                   forms.Select(attrs={'widget_name': 'language_usage'}, choices=(UserLanguage.LANGUAGE_USE_CHOICES)),
                   forms.Select(attrs={'widget_name': 'language_preferred'}, choices=(UserLanguage.LANGUAGE_PREFERENCE_CHOICES))
                   )
        super(LanguageFieldsWidget, self).__init__(widgets, attrs)

    def render(self, name, value, attrs=None):
        # value is a list of values, each corresponding to a widget
        # in self.widgets.
        if not isinstance(value, list):
            value = self.decompress(value)
        output = []
        #pdb.set_trace()
        for i, widget in enumerate(self.widgets):
            try:
                widget_value = value[i]
                widget_name = widget.attrs.get('widget_name')
            except KeyError:
                widget_value = None
                widget_name = 'anonymous'
            output.append(widget.render(name + '_%s' % widget_name, widget_value, attrs))
        return self.format_output(output)
    
    def decompress(self, value):
        """ """
#        pdb.set_trace()
        if value:
            return value.split('#')
        return ['Ook', 'Ook!', 'eeeeegleeeeee!!!!!']

    def value_from_datadict(self, data, name):
        language_name = data.get(self.language_name_field % name)
        language_usage = data.get(self.language_usage_field % name)
        language_preferred = data.get(self.language_preferred_field % name)
        #pdb.set_trace()        
        if language_name and language_usage and language_preferred:
            return  [language_name, language_usage, language_preferred]
        return None
     
##============================================================================##
## Classes below here are deprecated.
##============================================================================##
